import qs from 'qs';
var S4 = function () {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
var getFmtDate = function (date, fmt = 'yyyy-MM-dd') {
  if (!date) { return ''; }
  if (date instanceof Array) {
    return date.map(n => getFmtDate(new Date(n))).join(',');
  }
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};

const city = {
  11: '北京',
  12: '天津',
  13: '河北',
  14: '山西',
  15: '内蒙古',
  21: '辽宁',
  22: '吉林',
  23: '黑龙江',
  31: '上海',
  32: '江苏',
  33: '浙江',
  34: '安徽',
  35: '福建',
  36: '江西',
  37: '山东',
  41: '河南',
  42: '湖北',
  43: '湖南',
  44: '广东',
  45: '广西',
  46: '海南',
  50: '重庆',
  51: '四川',
  52: '贵州',
  53: '云南',
  54: '西藏',
  61: '陕西',
  62: '甘肃',
  63: '青海',
  64: '宁夏',
  65: '新疆',
  71: '台湾',
  81: '香港',
  82: '澳门',
  91: '国外 '
};

/* eslint-enable */
function identityCodeValid (code) {
  code && (code = code.toUpperCase());
  let pass = true;
  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/i.test(code)) {
    // 简单正则
    pass = false;
  } else if (!city[code.substr(0, 2)]) {
    // 地址编码错误
    pass = false;
  } else if (!birthDayValidate(code)) {
    pass = false;
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length == 18) {
      code = code.split('');

      // ∑(ai×Wi)(mod 11)
      // 加权因子
      const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

      // 校验位
      const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
      let sum = 0;
      let ai = 0;
      let wi = 0;
      for (let i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
      if (parity[sum % 11] != code[17]) {
        // 校验位错误
        pass = false;
      }
    }
  }
  return pass;
}
function birthDayValidate (idCard18) {
  const year = idCard18.substring(6, 10);
  const month = idCard18.substring(10, 12);
  const day = idCard18.substring(12, 14);
  const tempDate = new Date(year, parseFloat(month) - 1, parseFloat(day));
  if (tempDate.getFullYear() != parseFloat(year) || tempDate.getMonth() != parseFloat(month) - 1 || tempDate.getDate() != parseFloat(day)) {
    return false;
  }
  return true;
}

export default {
  stringify: (origin = {}) => {
    var newObj = {};
    Object.keys(origin).forEach(function (key) {
      if (origin[key] && origin[key] instanceof Array) {
        newObj[key] = origin[key].join(',');
      } else {
        newObj[key] = origin[key];
      }
    });
    return qs.stringify(newObj);
  },
  stringify2: (origin = {}) => {
    var str = '';
    Object.keys(origin).forEach(function (key) {
      if (origin[key] && origin[key] instanceof Array) {
        str += (key + '=' + origin[key].join(','))
      } else {
        str +=(key + '=' + origin[key])
      }
      str += '&'
    });
    return str.slice(0, -1);
    
  },
	idCardValidator: (value) => {
		if (value == '') {
			return '请输入身份证号';
		} else if (identityCodeValid(value)) {
			return '';
		} else {
			return '请输入合法的身份证号';
		}
	},
	analyzeIDCard: function(IDCard){
	    //获取用户身份证号码
	    var userCard = IDCard;
	    //如果身份证号码为undefind则返回空
	    if(!userCard){
	        return false;
	    }
	    //获取出生年月日
	    var yearBirth = userCard.substring(6,10);
	    var monthBirth = userCard.substring(10,12);
	    var dayBirth = userCard.substring(12,14);
	    //获取当前年月日并计算年龄
	    var myDate = new Date();
	    var monthNow = myDate.getMonth() + 1;
	    var dayNow = myDate.getDate();
	    var age = myDate.getFullYear() - yearBirth;
	    if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
	        age--;
	    }
	    if (age >= 18) { return true; }
	    return false;
	},
  getFmtDate,
  getQueryString: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
  },
  toggleAttr: function (arr, index, attrName = 'active') {
    arr.forEach(element => {
        element[attrName] = false;
    });
    if (index instanceof Function) {
      index = arr.findIndex(index);
    }
    arr[index] && (arr[index][attrName] = true);
  },
  getRandomRgbColor: function () {
    return new Array(3).fill(255).map((o) => {
      return o * Math.random();
    });
  },
  uuid: function () {
   return S4() + S4() + S4();
  },
  filterUtil: (list, name, type = 'type') => {
    return list.filter((o) => o[type] == name);
  },
  
  splitFmt: function (v, p = '') {
    return v.split(p).map(n => '<p>' + n + '</p>').join('');
  },
  isNewEvent (date) {
    if (date) {
      return Date.now() - new Date(date) < 5 * 60000;
    }
    return false;
  },
  cloneObject: function (obj) {
    return JSON.parse(JSON.stringify(obj));
  },
	mergeVariables: function (arr, vars, name, force) {
		if (!arr || !name) {
			return;
		}
		var length = vars.length;
		arr.forEach((n, i) => {
			if (n[name] && !force) {
				return;
			} else {
				n[name] = vars[i % length];
			}
		});
	},
	getAssert(assert, item) {
		var prop = assert[0];
		var targetVal = assert[1];
		return item[prop] == targetVal;
	},
	isJSON(target) {
	  return typeof target == "object" && target.constructor == Object;
	},
	mergeJSON (minor, main = {}) {
	  var main = this.cloneObject(main);
	  for (var key in minor) {
	    if (main[key] === undefined) {  // 不冲突的，直接赋值
	      main[key] = minor[key];
	      continue;
	    }
	
	    // 冲突了，如果是Object，看看有么有不冲突的属性
	    // 不是Object 则以main为主，忽略即可。故不需要else
	    if (this.isJSON(minor[key])) {
	      // arguments.callee 递归调用，并且与函数名解耦
	      main[key] = this.mergeJSON(minor[key], main[key]);
	    }
	  }
	  return main;
	}
};
